import sys
import re
import time
import pyautogui
import os.path
from datetime import datetime
import logging  # 引入logging模块
import random


class Android:
    def __init__(self):
        self.application = "安卓应用"
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)  # Log等级总开关
        # 第二步，创建一个handler，用于写入日志文件
        self.rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
        self.log_path = os.path.dirname(os.getcwd()) + '/Logs/' + self.application
        try:
            os.makedirs(self.log_path)
        except:
            pass
        self.logfile = self.log_path + '/' + self.rq + '.log'
        self.fh = logging.FileHandler(self.logfile, mode='w')
        self.fh.setLevel(logging.DEBUG)
        self.formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
        self.fh.setFormatter(self.formatter)
        self.logger.addHandler(self.fh)
        pyautogui.moveTo(x=0, y=0, duration=0.5, tween=pyautogui.linear)
        pyautogui.FAILSAFE = False
        self.logger.info("*" * 20 + "当前测试程序：" + self.application + "*" * 20)
        pyautogui.PAUSE = 2

    def monkey(self, x, y):
        x_ = (x - 323, x + 100)
        y_ = (y + 40, y + 800)
        x = random.randint(x_[0], x_[1])
        y = random.randint(y_[0], y_[1])
        pyautogui.typewrite(message="hello world", interval=0.1)
        pyautogui.moveTo(x, y)
        pyautogui.click()
        pyautogui.dragRel(xOffset=100, yOffset=100)
        pyautogui.doubleClick()
        pyautogui.scroll(-50)

    def start(self, app):
        try:
            self.logger.info("当前测试程序" + app)
            os.system("startapp " + app)
            time.sleep(10)
            x, y, w, h = pyautogui.locateOnScreen('./Pictures/commonly_pics/close.png', grayscale=True, confidence=0.7)
            pyautogui.moveTo(x, y)
            pyautogui.click()
        except:
            self.logger.error("当前程序出现错误" + app)

    def screen(self, app):

        self.logger.info("当前测试程序" + app)
        os.system("startapp " + app)
        time.sleep(4)
        x, y, w, h = pyautogui.locateOnScreen('./commonly_pics/sanlian.png', grayscale=True,
                                              confidence=0.7)
        im1 = pyautogui.screenshot(region=(x - 323, y, 480, 843))
        im1.save("./appPng/" + now_day + "/" + str(app) + "1.png")
        for i in range(5):
            self.monkey(x, y)
        im2 = pyautogui.screenshot(region=(x - 323, y, 480, 843))
        im2.save("./appPng/" + now_day + "/" + str(app) + "2.png")
        try:
            x, y, w, h = pyautogui.locateOnScreen('./commonly_pics/close.png', grayscale=True, confidence=0.7)
        except:
            pass
        pyautogui.moveTo(x, y)
        pyautogui.click()


if __name__ == '__main__':
    import os

    now_day = datetime.now().strftime("%Y-%m-%d")
    try:
        os.makedirs("./appPng/" + now_day)
    except:
        pass
    os.system("ls /home/kylin/.local/share/applications/*.desktop> apk.txt")
    ifile = "apk.txt"
    with open(ifile, 'r', encoding='utf8') as f:
        res = f.read()

    datas = re.findall(".*share/applications/(.*?).desktop", res)
    android = Android()
    while True:
        for i in datas:
            android.screen(i)
